<template>
  <div class="table-adn-barline-marker-wrapper">
    <div class="content-wrapper">
      <div class="body-left">
        <Card>
          <div slot="title">
            <div class="filter-wrapper">
              <Button @click="submitData" type="primary" size="small" style="margin-right: 10px;">提交修改</Button>
              <Button @click="saveData" type="info" size="small" style="margin-right: 10px;">保存</Button>
              <Button @click="showMeterDetail" type="warning" size="small">表具详情</Button>
            </div>
          </div>
          <div class="table-box">
            <Table
              ref="table"
              class="table-item"
              :height="tableHeight"
              :columns="tableColums"
              :loading="tableLoading"
              @on-row-click="onRowClickHandle"
              @on-row-dblclick="onRowDblclickHandle"
              :row-class-name="rowClassName"
              highlight-row
              size="small"
              :data="tableData"
            ></Table>
            <div class="page-box tc">
              <Page
                :total="tablePageData.total"
                size="small"
                simple
                @on-change="changeTablePageHandle"
                :page-size="tablaPageParams.pageSize"
              />
            </div>
          </div>
        </Card>
      </div>
      <div class="body-right">
        <div class="top-box">
          <Card>
            <e-candlestick id="tableAndElineCandlestick" :chartData="candlestickData" />
          </Card>
        </div>
        <div class="bottom-box">
          <Card>
            <echart-barline-marker
              id="zhexian"
              :chartData="zhexianDayData"
              :options="eLineByDayOptions"
              :markPointData="currentMarkData"
              :selectedPoints="zhexianSelectedPoints"
              @contextmenu="zhexianContextMenuSelectHandle"
              @clickSeries="zhexiantuClickHandle"
            />
          </Card>
        </div>
      </div>
    </div>
    <Modal
      v-model="showKxianFlag"
      class="kxian-modal"
      title="详情"
      @on-cancel="onKxianCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <div class="chart-box">
        <div :is="detailComponent" :options="gasUseDetailOptions"></div>
      </div>
      <div slot="footer">
        <Button @click="onKxianCancel" ghost>关闭</Button>
      </div>
    </Modal>

    <!-- 表具详情 -->
    <Modal
      key="tableAndBarlineMeterDetailModal"
      v-model="showMeterDetailModalFlag"
      class="meter-detail-modal"
      title="详情"
      @on-cancel="meterDetailModalCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <div
        id="tableAndBarlineMeterDetail"
        :is="userAndMeterInfoTpl"
        :content="meterDetailData"
        :currentMeterId="currentMeterId"
      ></div>
      <div slot="footer">
        <Button @click="meterDetailModalCancel" ghost>关闭</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { each, isUndefined, last, merge } from 'lodash'
import { kxianData, getMeterUnitDetail } from '@/api/tableAndBarlineMarker'
import { tableData } from '@/api/linkRatio'
import operateElineMixin from '@/mixins/operateEline'
import setTableHeightMixin from '@/mixins/setTableHeight'
import tableKeyUpToolMixin from '@/mixins/tableKeyUpTool'
import tableColums from './tableColums'
import { eLineByDayOptions, eCandlestickOptions } from './chartOptions/index'

export default {
  name: 'operateTable-day',
  mixins: [operateElineMixin, setTableHeightMixin, tableKeyUpToolMixin],
  props: {
    params: {
      type: Object
    }
  },
  components: {
    EchartBarlineMarker: () => import('@/commons/charts/EchartBarlineMarker'),
    ECandlestick: () => import('@/commons/charts/ECandlestick'),
    OperateECandlestickAndEline: () => import('@/commons/OperateECandlestickAndEline'),
    UserAndMeterDetailETree: () => import('@/commons/UserAndMeterDetailETree')
  },
  data() {
    return {
      tableLoading: false,
      tableData: [],
      tablaPageParams: {
        pageNum: 1,
        pageSize: 20
      },
      tablePageData: {
        total: 0
      },
      rowTimer: null,
      zhexianDayData: null,
      selectedData: null,
      hasMoveFlag: false,
      currentMarkData: [],
      resultSubmitData: [],
      showKxianFlag: false,
      gasUseDetailOptions: {
        meterId: null,
        month: null
      },
      detailComponent: null,
      candlestickData: null,
      zhexianSelectedPoints: null,
      zhexianKeyUpSelecteIndex: 0,
      zhexiantuFinishedStatus: false,
      zhexiantuHasSelected: false,
      options: {},
      showMeterDetailModalFlag: false,
      meterDetailData: null,
      userAndMeterInfoTpl: null,
      showDetailLoading: false,
      currentMeterId: null
    }
  },
  computed: {
    defaultDate() {
      return this.$config.nowDate
    },
    tableColums() {
      return tableColums
    },
    eLineByDayOptions() {
      return eLineByDayOptions
    }
  },
  mounted() {
    this.fetchTableData()
    const { meterId } = this.params
    // 当有meterId表示用户是选中数据进入页面，默认显示一条数据
    if (meterId) {
      this.init()
    }
  },
  methods: {
    /**
     * desc: 默认选中数据初始化
     * param {type}
     * return: void
     */
    init() {
      const { meterId, currentDate } = this.params
      this.currentMeterId = meterId
      const date = currentDate || this.defaultDate
      this.fetchKxianData({
        meterId,
        tId: date
      })
      this.fetchZhexianByDayData({
        meterId,
        days: date
      })
      // 绑定事件
      this.dispatchEvent()
    },
    meterDetailModalCancel() {
      this.showMeterDetailModalFlag = false
      this.hasMoveFlag = false
      this.meterDetailData = null
      this.userAndMeterInfoTpl = null
    },
    /**
     * @msg: 表格中数据异常列突出显示
     * @param {type}
     * @return:
     */
    rowClassName(row = {}) {
      const { status } = row
      if (Number(status) === 1) {
        return 'row-abnormal'
      }
      return ''
    },
    onKxianCancel() {
      this.detailComponent = null
      this.showKxianFlag = false
      this.hasMoveFlag = false
    },
    /**
     * @msg: 键盘操作折线图
     * @param {type}
     * @return:
     */
    keyUpSetZhexianData(type) {
      const { seriesData = [] } = this.zhexianDayData
      const sData = seriesData[this.zhexianKeyUpSelecteIndex]
      const selectData = {
        ...sData,
        index: sData.name - 1
      }
      this.zhexianContextMenuSelectHandle(selectData, type)
    },
    /**
     * @msg: 选取当前选中的数据项,并请求折线图数据
     * @param {type}
     * @return:
     */
    currentSelectedTableData() {
      const currentData = this.tableData[this.selectedIndex]
      this.selectedData = currentData
      const { meterId } = currentData
      const { currentDate } = this.params
      this.currentMeterId = meterId
      this.options = {
        ...this.options,
        meterId
      }
      const date = currentDate || this.defaultDate
      this.fetchZhexianByDayData({
        meterId,
        days: date
      })
      this.fetchKxianData({
        meterId,
        tId: date
      })
    },
    /**
     * @msg: 表格页面修改
     * @param {type}
     * @return:
     */
    changeTablePageHandle(data) {
      this.tablaPageParams = {
        ...this.tablaPageParams,
        pageNum: data
      }
      this.$nextTick(() => {
        this.fetchTableData()
      })
    },
    /**
     * @msg: 表格行点击
     * @param {type}
     * @return:
     */
    onRowClickHandle(row, index) {
      const { meterId } = row
      this.currentMeterId = meterId
      clearTimeout(this.rowTimer)
      this.rowTimer = setTimeout(() => {
        if (isUndefined(this.selectedIndex)) {
          this.dispatchEvent()
        }
        if (this.selectedIndex !== index) {
          this.selectedIndex = index
          this.$nextTick(() => {
            this.currentSelectedTableData()
          })
        }
      }, 300)
    },
    onRowDblclickHandle(row, index) {
      clearTimeout(this.rowTimer)
      const { currentDate = undefined } = this.params
      const { meterId } = row
      this.currentMeterId = meterId
      this.gasUseDetailOptions = {
        ...this.gasUseDetailOptions,
        meterId,
        month: currentDate && dayjs(currentDate).format('YYYY-MM'),
        day: currentDate
      }
      this.showKxianFlag = true
      this.hasMoveFlag = true
      this.detailComponent = 'OperateECandlestickAndEline'
    },
    /**
     * @msg: 这里表格数据
     * @param {type}
     * @return:
     */
    modifyTabelData(data = {}) {
      const { list = [], total, pageNum, pageSize } = data
      const { meterId } = this.params
      // 选中数据进来默认选中第一条数据
      if (meterId) {
        list[0]._highlight = true
      }
      this.tableData = list
      this.tablePageData = {
        ...this.tablePageData,
        total,
        pageSize,
        pageNum
      }
      this.$nextTick(() => {
        this.setTableHeight()
      })
    },
    /**
     * @msg: 获取表格数据
     * @param {type}
     * @return:
     */
    fetchTableData() {
      const { gasClass, ...rest } = this.params
      this.tableLoading = true
      tableData({
        ...this.tablaPageParams,
        ...rest,
        meterGasClass: gasClass,
        order: 'asc'
      })
        .then(res => {
          this.tableLoading = false
          if (res.date) {
            this.modifyTabelData(res.date)
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    /**
     * @msg: 指数图数据
     * @param {type}
     * @return:
     */
    modifyRectTreeMapData(rawData = []) {
      let xAixisList = []
      let values = []
      const actualGas = []
      const markPointData = []
      each(rawData, item => {
        const [first, one, two, three, four, five] = item
        xAixisList.push(first)
        let color0 = '#ec0000'
        let borderColor0 = '#8A0000'
        let color = '#00da3c'
        let borderColor = '#008F28'
        const lastItem = last(item)
        if (lastItem) {
          color0 = '#ff9900'
          borderColor0 = '#ff9900'
          color = '#ff9900'
          borderColor = '#ff9900'
          markPointData.push({
            name: first,
            value: two,
            coord: [first, two],
            itemStyle: {
              color: '#ff9900'
            }
          })
        }
        if (five < 0) {
          color0 = '#ed141e'
          borderColor0 = '#ed141e'
          color = '#ed141e'
          borderColor = '#ed141e'
        }
        values.push({
          name: first,
          value: [one, two, four, three],
          itemStyle: {
            color,
            borderColor,
            borderColor0,
            color0
          }
        })
        actualGas.push(five)
      })

      return {
        xAixisList,
        values: {
          data: values,
          markPointData
        },
        actualGas
      }
    },
    fetchKxianData(params) {
      kxianData(params).then(res => {
        if (res.date) {
          const { xAixisList, values, actualGas } = this.modifyRectTreeMapData(res.date)
          this.candlestickData = merge({}, eCandlestickOptions, {
            xAxis: {
              data: xAixisList
            },
            series: [
              {
                data: values.data,
                markPoint: {
                  data: values.markPointData
                }
              },
              {
                data: actualGas
              }
            ]
          })
        }
      })
    },
    /**
     * @msg: 帅选出折线图点击点
     * @param {type}
     * @return:
     */
    getZhexianSelectedPoint() {
      this.$nextTick(() => {
        const { seriesData = [] } = this.zhexianDayData
        const selecteData = seriesData[this.zhexianKeyUpSelecteIndex]
        const { name, value } = selecteData
        const retData = {
          ...selecteData,
          value: [name - 1, value]
        }
        this.zhexianSelectedPoints = [
          {
            data: [retData],
            type: 'effectScatter'
          }
        ]
      })
    },
    /**
     * @msg: 折线图点击
     * @param {type}
     * @return:
     */
    zhexiantuClickHandle(params = {}) {
      const { data = {} } = params
      this.zhexiantuFinishedStatus = true
      this.zhexiantuHasSelected = true
      const { index } = data
      this.zhexianKeyUpSelecteIndex = index
      this.getZhexianSelectedPoint()
    },
    /**
     * @msg: 显示表具详情
     * @param {type}
     * @return:
     */
    showMeterDetail() {
      if (!this.currentMeterId) {
        return this.showWraningNotice('', '请选择数据后再操作')
      }
      this.showDetailLoading = true
      this.$Loading.start()
      getMeterUnitDetail(this.currentMeterId)
        .then(res => {
          this.showDetailLoading = false
          this.$Loading.finish()
          if (res.date) {
            this.meterDetailData = res.date
            this.userAndMeterInfoTpl = 'UserAndMeterDetailETree'
            this.showMeterDetailModalFlag = true
            this.hasMoveFlag = true
          }
        })
        .catch(e => {
          this.showDetailLoading = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
